/*补充的常用js插件*/
/*swiper*/
var swiper ={
    init:function () {
        if ($('.swiper-container').length > 0) {
            In('swiper', function () {
                $('.swiper-container').each(function () {
                    var $option = $(this).data('option');
                    var id = $(this).attr('id');
                    $option = utils.parseOptions($option);
                    var option = $option || {};
                    var defaultOptions = {

                    };
                    var options = $.extend({}, defaultOptions, option);
                    new Swiper('#'+id,options);
                })
            });
        }
    }
};
/*数字加减*/
var alignmentFns = {
    inputs: [],
    init: function(input, step, max, min, digit) {
        var _this = this;
        input.attr("readonly", "readonly");

        //添加左右加减号
        input.wrap("<div id = '" + input.attr('id') + "div' class = 'mc-adjust'></div>");
        input.before("<span id = '" + input.attr('id') + "l'  onselectstart = 'return false;' class='j_dec'></span>");
        input.after("<span id = '" + input.attr('id') + "r'  onselectstart = 'return false;' class = 'j_inc'></span>");
        //左右调用执行
        $("#" + input.attr('id') + "l").click(function() {
            _this.execute(input, step, max, min, digit, true);
        });
        $("#" + input.attr('id') + "r").click(function() {
            _this.execute(input, step, max, min, digit, false);
        });
    },
    execute: function(input, step, max, min, digit, _do) {
        var val = parseFloat(this.format(input.val(), digit));
        var ori = val;
        if (_do) val -= step;
        if (!_do) val += step;
        if (val < min) {
            val = min;
        } else if (val > max) {
            val = max;
        }
        input.val(this.format(val, digit)).change();
    },
    format: function(val, digit) {
        if (isNaN(val)) {
            val = 0;
        }
        return parseFloat(val).toFixed(digit);
    },
    // 类型
    data: {
        default_data: {
            "step": 0.1,
            "min": 0,
            "max": 99,
            "digit": 1
        }
    },
    // 初始化
    initialize: function() {
        //使用控件必须有以下属性或者引用alignment类
        var inputs = $("input[user_data], input[data-digit], input[data-step], input[data-min], input[data-max],input[data-class], input.alignment");


        inputs.each(function() {
            // 记录原始input代码
            alignmentFns.inputs.push(this.outerHTML);
            //预设值数据选择
            var data = alignmentFns.data;

            var user_data = eval("data." + $(this).attr("user_data"));
            if (user_data == null) {
                user_data = JSON.parse(JSON.stringify(data.default_data));
            }

            var digit = $(this).data("digit");
            if (digit != null && !isNaN(parseFloat(digit))) {
                digit = parseFloat(digit).toFixed(0);
                user_data.digit = parseFloat(digit);
            }

            var step = $(this).data("step");
            if (step != null && !isNaN(parseFloat(step))) {
                user_data.step = parseFloat(step);
            }
            var min = $(this).data("min");
            if (min != null && !isNaN(parseFloat(min))) {
                user_data.min = parseFloat(min);
            }

            var max = $(this).data("max");
            if (max != null && !isNaN(parseFloat(max))) {
                user_data.max = parseFloat(max);
            }
            //自动装载
            alignmentFns.init($(this), user_data.step, user_data.max, user_data.min, user_data.digit);

            var data_edit = $(this).data("edit");
            if (data_edit) {
                $(this).attr("readonly", null);
            }
            var data_class = $(this).data("class");
            if (data_class!='') {
                $(this).parents(".mc-adjust").addClass(data_class);
            }

        });
    },
    destroy: function() {
        var inputs = this.inputs;
        $.each(inputs, function(index, obj) {
            var input = $(obj)[0];
            var id = input.id;
            $("#" + id + "div").replaceWith(input);
        });
    },
    // 动态添加类型
    createType: function(types) {
        $.each(types, function(index, obj) {
            alignmentFns.data[obj.type] = obj.data;
        });
    }
};
var utils = {
    /**
     * 格式化参数
     * @param string
     */
    parseOptions: function (string) {
        if ($.isPlainObject(string)) {
            return string;
        }

        var start = (string ? string.indexOf('{') : -1),
            options = {};

        if (start != -1) {
            try {
                options = (new Function('', 'var json = ' + string.substr(start) + '; return JSON.parse(JSON.stringify(json));'))();
            } catch (e) {
            }
        }
        return options;
    },
    //是否手机
    isMobile: function () {
        var ua = navigator.userAgent;
        var ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
            isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
            isAndroid = ua.match(/(Android)\s+([\d.]+)/),
            isMobile = isIphone || isAndroid;
        if (isMobile) {
            return 1;
        } else {
            return 0;
        }
    },
    //刷新页面
    refreshPage: function () {
        window.location.reload();
        return false;
    },
    //返回上一页
    back: function () {
        window.history.back(-1);
    },
    //跳转地址
    urlHref: function (url) {
        window.location.href = url;
    },
    //复选框全选
    checkAll: function (dom) {
        var obj = dom || '#grid';
        $(obj + " :checkbox").prop("checked", true);
    },
    //复选框反选
    checkOther: function (dom) {
        var obj = dom || '#grid';
        $(obj + " :checkbox").each(function () {
            $(this).prop("checked", !$(this).prop("checked"));
        });
    },
    //获取复选框值
    getCheckboxValue: function (dom,type) {
        var obj = dom || '#grid';
        var res = type || 'str';
        var reVal = [];
        $(obj).find("input[type='checkbox']").each(function () {
            if ($(this).prop("checked")) {
                reVal.push($(this).val());
            }
        });
        if(res=='str'){
            return reVal.join(',');
        }else{
            return reVal;
        }
    },
    //获取json指定列数据
    jsonCol: function (json, col, split) {
        var len = json.length;
        var strsplit = split || ',';
        if (len == 0) {
            return [];
        } else {
            var reval = [];
            for (var i = 0; i < len; i++) {
                reval.push(json[i][col]);
            }
            return reval.join(strsplit);
        }
    },
    //json转字符串
    json2string: function (json) {
        return JSON.stringify(json);
    },
    //时间戳友好显示
    dateDiff: function (timestamp) {
        // 补全为13位
        var arrTimestamp = (timestamp + '').split('');
        for (var start = 0; start < 13; start++) {
            if (!arrTimestamp[start]) {
                arrTimestamp[start] = '0';
            }
        }
        timestamp = arrTimestamp.join('') * 1;
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime();
        var diffValue = now - timestamp;
        // 如果本地时间反而小于变量时间
        if (diffValue < 0) {
            return '不久前';
        }
        // 计算差异时间的量级
        var monthC = diffValue / month;
        var weekC = diffValue / (7 * day);
        var dayC = diffValue / day;
        var hourC = diffValue / hour;
        var minC = diffValue / minute;

        // 数值补0方法
        var zero = function (value) {
            if (value < 10) {
                return '0' + value;
            }
            return value;
        };
        // 使用
        if (monthC > 12) {
            // 超过1年，直接显示年月日
            return (function () {
                var date = new Date(timestamp);
                return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
            })();
        } else if (monthC >= 1) {
            return parseInt(monthC) + "月前";
        } else if (weekC >= 1) {
            return parseInt(weekC) + "周前";
        } else if (dayC >= 1) {
            return parseInt(dayC) + "天前";
        } else if (hourC >= 1) {
            return parseInt(hourC) + "小时前";
        } else if (minC >= 1) {
            return parseInt(minC) + "分钟前";
        }
        return '刚刚';
    },
    //格式化时间戳
    dateFormat: function (timestamp, formats) {
        // formats格式包括
        // 1. Y-m-d
        // 2. Y-m-d H:i:s
        // 3. Y年m月d日
        // 4. Y年m月d日 H时i分
        formats = formats || 'Y-m-d';

        var zero = function (value) {
            if (value < 10) {
                return '0' + value;
            }
            return value;
        };
        timestamp = timestamp * 1000;
        var myDate = timestamp ? new Date(timestamp) : new Date();

        var year = myDate.getFullYear();
        var month = zero(myDate.getMonth() + 1);
        var day = zero(myDate.getDate());

        var hour = zero(myDate.getHours());
        var minite = zero(myDate.getMinutes());
        var second = zero(myDate.getSeconds());

        return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
            return ({
                Y: year,
                m: month,
                d: day,
                H: hour,
                i: minite,
                s: second
            })[matches];
        });
    },
    loading:function () {
        $.showLoading();
        setTimeout(function() {
            $.hideLoading();
        }, 3000)
    },
    hideloading:function () {
        $.hideLoading();
    },
    toptip:function(msg,duration,type){
        $.toptip(msg, duration, type);
    },
    /*$.toptip('操作成功', 'success');
    $.toptip('操作失败', 'error');
    $.toptip('警告', 'warning');
    $.toptip('操作成功', 2000, 'success');  //设置显示时间
    */
    tips: function (msg) {
        $.toast(msg, "text");
    },
    msg: function (msg,times) {
        var times=times||2000;
        $.toast(msg,times);
    },
    error: function (msg, callfn) {
        $.toast(msg, "cancel", callfn);
    },
    success: function (msg, callfn) {
        $.toast(msg, callfn);
    },
    confirm: function (msg, onOK, onCancel) {
        $.confirm(msg, "提示消息", onOK, onCancel);
    },
    //确认后操作
    doAction: function (obj, callfn) {
        var that = this;
        var msg = $(obj).data('msg') || '确认操作吗？';
        var url = $(obj).data('url');
        var params = $(obj).data('params');
        utils.confirm(msg,function (index) {
            that.getAjax({
                url: url,
                data: params,
                success: function (res) {
                    if (res.code == 1) {
                        if (typeof callfn === "function") {
                            callfn(obj, res);
                        } else {
                            if (callfn == "refreshPage") that.refreshPage();
                            if (callfn == 'url') that.urlHref(res.url);
                        }
                    } else {
                        utils.error(res.msg);
                    }
                }
            });
        });
    },
    //获取url参数
    getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },
    //表单验证
    ajaxSubForm: function (options, dom) {
        var obj = dom || '#form';
        var defaultConfig = {
            btnSubmit: ".btn-sub",
            btnReset: ".btn-reset",
            ajaxPost: true,
            postonce: true,
            tipSweep: true,
            label: '.control-label',
            tiptype: function (msg, o, cssctl) {
                var item = o.obj.closest('.weui-cell');
                var error_style = 'weui-cell_warn';
                if(item.length==0){
                    item = o.obj.closest('.form-group');
                    error_style = 'has-warning';
                }
                if (o.type == 3) {
                    item.addClass(error_style);
                    item.find('.valid-msg').show().html(msg);
                    utils.toptip(msg,'error');
                } else {
                    item.removeClass(error_style);
                    item.find('.valid-msg').html('').hide();
                }
            },
            beforeCheck: function (curform) {
                if (typeof CKEDITOR != 'undefined') { //同步编辑器
                    for (instance in CKEDITOR.instances) {
                        CKEDITOR.instances[instance].updateElement();
                    }
                }
            },
            beforeSubmit: function (curform) {
                $(obj).find('.btn-sub').attr("disabled", "disabled"); //禁用按钮
                $(obj).find('.btn-reset').attr("disabled", "disabled"); //禁用按钮
                $(obj).find("[type='submit']").attr("disabled", "disabled"); //禁用按钮
                $(obj).find("[type='reset']").attr("disabled", "disabled"); //禁用按钮
                utils.loading();
            },
            callback: function (res) {
                utils.hideloading();
                $(obj).find('.btn-sub').removeAttr("disabled"); //启用按钮
                $(obj).find('.btn-reset').removeAttr("disabled"); //启用按钮
                $(obj).find("[type='submit']").removeAttr("disabled"); //启用按钮
                $(obj).find("[type='reset']").removeAttr("disabled"); //启用按钮
                if (res.code == 1) {
                    if (typeof options == 'function') {
                        options(res);
                    }else{
                        var callfn = $(obj).data('callfn');
                        if (callfn == "refreshPage"){
                            utils.success(res.msg,function () {
                                utils.refreshPage();
                            })
                        }
                        if (callfn == 'url'){
                            utils.success(res.msg,function () {
                                utils.urlHref(res.url);
                            })
                        }
                    }
                } else {
                    utils.toptip(res.msg,'error');
                    //$(obj).find('.valid-msg').show().html('<i class="fa fa-bell-o"></i> ' + res.msg);
                }
            }
        };
        var config = defaultConfig;
        if (typeof options == 'object') {
            config = $.extend({}, defaultConfig, options);
        }
        In('valid', function () {
            $(obj).Validform(config);
        });
    },
    //ajax封装
    getAjax: function (options) {
        var defaultOptions = {
            type: 'post',
            cache: true,
            async: true,
            dataType: 'json',
            beforeSend: function () {
                utils.loading();
            },
            error: function () {
                utils.error('与服务器断开连接！');
                return false;
            },
            complete: function () {
                utils.hideloading();
            }
        };
        var option = $.extend({}, defaultOptions, options);
        $.ajax(option);
    },
    /*获取检索参数*/
    getParams:function (dom) {
        var obj = dom || '#searchForm';
        var params={};
        var filters={};
        var op={};
        if($(obj).length>0){
            var formData = $(obj).serializeArray();
            for (var i in formData) {
                //filter: {"createtime":"2018-10-26 00:00:00 - 2018-10-26 23:59:59","uid":1}
                //op: {"createtime":"BETWEEN","uid":"="}
                var opObj = $("[name='"+formData[i].name+"']");
                var opstr = opObj.data('op');
                var own = opObj.data('own');
                var value = formData[i]['value'];
                if(own=='1') { //单独传输
                    params[formData[i].name] = value;
                }else{
                    if(!valid.isEmpty(formData[i].name)){
                        op[formData[i].name]=opstr;
                        filters[formData[i].name]=value;
                    }
                }
            }
        }
        if($(obj).find('.search_key').length>0){
            params.searchKey=$(obj).find('.search_key').val();
        }
        if($(obj).find('.search_value').length>0){
            params.searchKey=$(obj).find('.search_value').val();
        }
        params.filter=filters;
        params.op=op;
        return params;
    },
    /*分页加载*/
    initPage:function (options,dom) {
        var obj = dom || '#page';
        var params = options.params || utils.getParams();
        In('paginationjs',function () {
            var defaultConfig = {
                locator:'rows',
                totalNumberLocator:function (response) {
                    return response.total;
                },
                className:'paginationjs-theme-blue',
                pageSize: 12,
                prevText:'上一页',
                nextText:'下一页',
                ajax: {
                    type:'post',
                    data:params,
                    beforeSend: function() {
                        utils.loading();
                    },
                    complete:function () {
                        utils.hideloading();
                    }
                }
            };
            var config = $.extend({}, defaultConfig, options);
            $(obj).pagination(config);
        });
    },
    /*下拉加载*/
    mescroll: function (dom,options,callback) {
        var defaultConfig = {
            page: {size: 10},
            auto: true,//初始化完毕,是否自动触发上拉加载的回调
            isBoth: false, //上拉加载时,如果滑动到列表顶部是否可以同时触发下拉刷新;默认false,两者不可同时触发; 这里为了演示改为true,不必等列表加载完毕才可下拉;
            isBounce: false, //此处禁止ios回弹,解析(务必认真阅读,特别是最后一点): http://www.mescroll.com/qa.html#q10
            clearEmptyId: dom+'-content',
            noMoreSize: 6,
            offset: 100,
            htmlNodata: '<p class="upwarp-nodata">-- END -- </p>',
            toTop: { //配置回到顶部按钮
                src: "/static/home/plugins/mescroll/mescroll-totop.png" //默认滚动到1000px显示,可配置offset修改
            }
        };
        var upconfig = $.extend({}, defaultConfig, options);
        In.config('serial',true);
        var demo = In('mescroll',function () {
            var mescroll = new MeScroll(dom, {up: upconfig});
            return mescroll;
        });
        return demo;

    },
    /*截取字符串*/
    msubstr:function (str,start,length,suffix) {
        var start = start || 0;
        var length = length || 10;
        var str_length=str.length;/*字符长度*/
        var new_str=str.substring(parseInt(start),parseInt(start)+parseInt(length));
        if(suffix==1 && str_length>length){
            return new_str+'...';
        }else{
            return new_str;
        }
    },
    /**
     * 格式化金额
     * moneyFormat("12345.675910", 3)，返回12,345.676
     * */
    moneyFormat:function (s,n) {
        n = n > 0 && n <= 20 ? n : 2;
        s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
        var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
        t = "";
        for (i = 0; i < l.length; i++) {
            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "" : "");
        }
        return t.split("").reverse().join("") + "." + r;

    },
    //图片预览
    imgPreview: function (url) {
        if (url == '') {
            utils.error('请先上传图片');
            return false;
        }
        if (utils.isMobile() == 1) {
            area = "80%";
            width = '100%';
        } else {
            area = '400px';
            width = '400px';
        }
        top.layer.open({
            type:1,
            title: false,
            closeBtn: 0,
            offset:'60px',
            area: area,
            shadeClose: true,
            content: '<img src="' + url + '" style="width:' + width + ';" />'
        });
    },
    //附件下载
    filePreview: function (url) {
        if(url==''){
            layer.msg('附件为空！');
            return false;
        }
        var $form = $('<form method="POST" target="_blank"></form>');
        $form.attr('action', url);
        $form.appendTo($('body'));
        $form.submit();
    },
    //删除行 父级元素是 .item-row 时通用
    delRow: function (obj, callFn) {
        $(obj).closest('.item-row').remove();
        if (typeof callFn != 'undefined') {
            callFn(obj);
        }
    },
    //上移 父级元素是 .item-row 时通用
    upMove: function (obj) {
        var leftMove = $(obj).closest('.item-row');   //当前行
        var prevMove = leftMove.prev('.item-row');               //上一个同级元素
        if (prevMove.length > 0) {                        //存在上一个同级元素
            prevMove.insertAfter(leftMove);           //就把它移动到前面
        }
    },
    //下移 父级元素是 .item-row 时通用
    downMove: function (obj) {
        var rightMove = $(obj).closest('.item-row');
        var nextMove = rightMove.next('.item-row');
        if (nextMove.length > 0) {
            nextMove.insertBefore(rightMove);
        }
    },
};
/**
 * 验证
 */
var valid = {
    //是否为空
    isEmpty: function (str) {
        if (str == "" || str == null || str == undefined) { // "",null,undefined
            return true;
        } else {
            return false;
        }
    },
    //是否为邮件
    isEmail: function (str) {
        var reg = /^\w+((-w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
        if (reg.test(str)) return true;
    },
    //是否为手机号
    isPhone: function (str) {
        var a = /^1\d{10}$/, s = $.trim(str);
        if (a.test(s)) return true;
    },
    //是否汉字
    isCN: function (str) {
        var s = $.trim(str), reg = /^[\u4e00-\u9fa5]+$/;
        if (reg.test(s)) return true;
        else return false;
    },
    //是否密码
    isPwd: function (str) {
        var reg = /^[A-Za-z0-9_-]+$/;
        if (reg.test(str)) return true;
    },
    //是否为微信号
    isWx: function (str) {
        var rex = /^[a-zA-Z\d_]{5,}$/;
        if (rex.test($.trim(str))) return true;
        return false;
    },
    //是否全为数字
    isNum: function (num) {
        var rex = /^[0-9]+$/;
        if (rex.test($.trim(num))) return true;
        return false;
    },
    //是否为热线电话
    isPhone: function (num) {
        var rex = /^[0-9]([0-9]|-)*[0-9]$/;
        if (rex.test($.trim(num))) return true;
        return false;
    },
    //是否为钱数
    isFloat: function (n) {
        return !isNaN(n);
    },
    //判断是否为url地址
    isUrl: function (str) {
        var rex = /^(http|https){1}:\/\/[^\s]+$/;
        if (rex.test($.trim(str))) return true;
        else return false;
    }
};
/**
 * 表单辅助
 */
var formHelper = {
    initForm: function () {
        var that = this;
        that.colorpicker();
        that.cxselect();
        that.selectpage();
        that.select2();
        that.uploadImage();
        that.uploadFile();
        that.uploadMedia();
        that.uploadMultiImage();
        that.uploadMultiImageDesc();
        that.uploadMultiFile();
        that.tags();
        that.inputArray();
        that.switch();
        that.ckeditor();
        that.lightBox();
    },
    colorpicker:function(){
        if ($('.f-colorpicker').length > 0) {
            In('colorpicker', function () {
                $('.f-colorpicker').colorpicker();
            });
        }
    },
    /*多行文本字数统计*/
    checkMaxInput:function (obj,maxLen) {
        if (obj == null || obj == undefined || obj == "") {
            return;
        }
        if (maxLen == null || maxLen == undefined || maxLen == "") {
            maxLen = 100;
        }
        var strResult;
        var $obj = $(obj);
        var newid = $obj.attr("id") + 'msg';
        if (obj.value.length > maxLen) { //如果输入的字数超过了限制
            obj.value = obj.value.substring(0, maxLen); //就去掉多余的字
            strResult = '<span id="' + newid + '" class=\'Max_msg\' ><br/>剩(' + (maxLen - obj.value.length) + ')字</span>'; //计算并显示剩余字数
        }
        else {
            strResult = '<span id="' + newid + '" class=\'Max_msg\' ><br/>剩(' + (maxLen - obj.value.length) + ')字</span>'; //计算并显示剩余字数
        }
        var $msg = $("#" + newid);
        if ($msg.length == 0) {
            $obj.after(strResult);
        }
        else {
            $msg.html(strResult);
        }
    },
    /*灯箱预览*/
    lightBox:function () {
        if ($('.f-lightbox').length > 0) {
            In('light-box', function (){
                $('.f-lightbox').each(function () {
                    var select = $(this).data('select');
                    var $option = $(this).data('option');
                    var option = $option || {};
                    var defaultOptions = {
                        wrap_class: 'lcl_fade_oc',
                        gallery : true,
                        thumb_attr: 'data-lcl-thumb',
                        skin: 'minimal',
                        radius: 0,
                        padding	: 0,
                        border_w: 0,
                    };
                    var options = $.extend({}, defaultOptions, option);
                    lc_lightbox('.'+select,options);
                });
            });
        }
    },
    /*cxselect*/
    cxselect:function () {
        if($('.f-cx-select').length >0 ){
            In('cxselect',function () {
                $('.f-cx-select').each(function () {
                    var id=$(this).attr('id');
                    var selects = $(this).data('selects');
                    var url = $(this).data('url');
                    valid.isEmpty(selects)?$(this).data('selects','prov,city,dist'):'';
                    valid.isEmpty(url)?$(this).data('url','/static/plugins/cxselect/js/cityData.min.json'):'';
                    $('#'+id).cxSelect({
                    },function(api) {
                        cxSelectApi=api;
                    });
                });
            })
        }
    },
    /*switch*/
    switch:function () {
        if ($('.f-switch').length > 0) {
            In('switch', function () {
                $('.f-switch').each(function () {
                    var $option = $(this).data('option');
                    var name = $(this).attr('name');
                    var option = $option || {};
                    var defaultOptions = {
                        onText:"启用",
                        offText:"禁用",
                        onColor:'success',
                        offColor:'danger',
                        size:"mini",
                        onSwitchChange:function(event,state){
                            if (typeof option['callfn'] != 'undefined') {
                                eval(option['callfn'] + '(event, state)');
                            }
                        }
                    };
                    var options = $.extend({}, defaultOptions, option);
                    $('input[name="'+name+'"]').bootstrapSwitch(options);
                })
            });
        }
    },
    //富文本编辑器
    ckeditor: function () {
        if ($('.f-ckeditor').length > 0) {
            In('ckeditor', function () {
                $('.f-ckeditor').each(function () {
                    var name = $(this).attr('name');
                    var $option = $(this).data('option');
                    var toolbar = $(this).data('toolbar');
                    if(valid.isEmpty(toolbar)){
                        var bodyWidth = $(document.body).width();
                        toolbar = bodyWidth <= 1024 ? 'Basic' : 'Full';
                    }
                    var option = valid.isEmpty($option) ? {} : $option;
                    var defaultOptions = {
                        toolbar: toolbar
                    };
                    var options = $.extend({}, defaultOptions, option);
                    var editor = CKEDITOR.replace(name, options);
                    //增加视频按钮
                    editor.ui.addButton && editor.ui.addButton( 'html5video', {
                        label   : 'Video',
                        command : 'html5video'
                    });
                });
            });
        }
    },

    //selectpage控件
    selectpage: function () {
        if ($('.f-selectpage').length > 0) {
            In('selectpage', function () {
                $('.f-selectpage').each(function () {
                    var url = $(this).data('url');
                    var showField = $(this).data('show');
                    var keyField = $(this).data('key');
                    var searchField = $(this).data('search');
                    searchField = searchField || showField;
                    var option = $(this).data('option');
                    option = option || {};
                    var query = $(this).data('query');
                    var custom = $(this).data('custom');
                    query = query || '';
                    custom = custom || '';
                    var defaultOptions = {
                        data: url,
                        showField: showField,
                        keyField: keyField,
                        dropButton: true,
                        multiple: false,
                        maxSelectLimit: 0,
                        andOr: 'AND',
                        pageSize: 10,
                        params: function () {
                            return {searchField:searchField,query: query,custom:custom};
                        },
                        eAjaxSuccess: function (d) {
                            return d ? d : undefined;
                        },
                    };
                    if (typeof option['formatItemFun'] != 'undefined') {
                        defaultOptions.formatItem = function (data) {
                            return eval(option['formatItemFun'] + '(data)');
                        }
                    }
                    if (typeof option['selectFun'] != 'undefined') {
                        defaultOptions.eSelect = function (data) {
                            return eval(option['selectFun'] + '(data)');
                        }
                    }
                    if (typeof option['tagRemove'] != 'undefined') {
                        defaultOptions.eTagRemove = function (datas) {
                            return eval(option['tagRemove'] + '(datas)');
                        }
                    }
                    if (typeof option['clear'] != 'undefined') {
                        defaultOptions.eClear = function () {
                            return eval(option['clear'] + '()');
                        }
                    }
                    var options = $.extend({}, defaultOptions, option);
                    $(this).selectPage(options);
                });
            });
        }
    },
    //select2
    select2: function () {
        if ($('.f-select2').length > 0) {
            In('select2', function () {
                $('.f-select2').each(function () {
                    var $option = $(this).data('option');
                    var name = $(this).attr('name');
                    var option = valid.isEmpty($option) ? {} : $option;
                    var defaultOptions = {
                        placeholder: '请选择',
                        //minimumResultsForSearch:Infinity // 隐藏搜索框
                    };
                    var options = $.extend({}, defaultOptions, option);
                    $('select[name="'+name+'"]').select2(options);
                    /*设置初始值*/
                    var value = $(this).data('value');
                    if(!valid.isEmpty(value) && !valid.isNum(value)) {
                        value = value.split(',');
                    }
                    $('select[name="'+name+'"]').val(value).trigger('change');
                })
            });
        }
    },
    //上传图片
    uploadImage: function () {
        if ($('.f-uploadimg').length > 0) {
            In('upload', function () {
                $('.f-uploadimg').each(function () {
                    var id = $(this).attr('id');
                    /*忽略300毫秒延迟*/
                    $(this).addClass('needsclick');
                    var $option = $(this).data('option'); //maxsize
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '10mb';
                    var ext = $option['ext'] || 'jpg,gif,png';
                    var defaultOptions={
                        runtimes: 'html5,flash,html4',
                        multi_selection: false, //不允许多选
                        browse_button: id,
                        url: '/home/upload/file.html?ext_type=img',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择图片", extensions: ext}
                            ],
                            prevent_duplicates : true //不允许队列中存在重复文件
                        },
                        resize: {
                            width: 1000,
                            crop: false,
                            quality : 90,
                            preserve_headers: true
                        },
                        init: {
                            Error:function (uploader,errObject) {
                                utils.error(errObject.message);
                            },
                            FilesAdded: function (up, files) {
                                utils.loading();
                                up.start();
                            },
                            UploadProgress: function(up, file) { //上传中，显示进度条
                                var percent = file.percent;
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').show();
                                    $('#'+id+'-progress').find('.progress-bar').css({"width": percent + "%"});
                                }
                            },
                            FileUploaded: function (up, file, responseObject) {
                                utils.hideloading();
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').hide();
                                }
                                if (responseObject.status === 200) {
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        $('#input-' + id).val(res.url);
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        }
                                    } else {
                                        utils.error(res.error.message);
                                    }
                                } else {
                                    utils.tips('上传服务器无响应！');
                                }
                            },
                            Error: function(up, err) {
                                if(err.code==-200){
                                    utils.error("文件格式错误，请检查后重新上传!");
                                }
                            }
                        }
                    };
                    var options = $.extend({}, defaultOptions, $option);
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    //上传附件
    uploadFile: function () {
        if ($('.f-uploadfile').length > 0) {
            In('upload', function () {
                $('.f-uploadfile').each(function () {
                    var id = $(this).attr('id');
                    /*忽略300毫秒延迟*/
                    $(this).addClass('needsclick');
                    var $option = $(this).data('option'); //maxsize
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '50mb';
                    var ext = $option['ext'] || 'rar,zip,tar,gz,7z,bz2,cab,iso,pem,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,md,jpg,jpeg,png,gif';
                    var defaultOptions={
                        runtimes: 'html5,flash,html4',
                        multi_selection: false, //不允许多选
                        browse_button: id,
                        url: '/home/upload/file.html?ext_type=file',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择附件", extensions: ext}
                            ]
                        },
                        init: {
                            Error:function (uploader,errObject) {
                                utils.error(errObject.message);
                            },
                            FilesAdded: function (up, files) {
                                utils.loading();
                                up.start();
                            },
                            UploadProgress: function(up, file) { //上传中，显示进度条
                                var percent = file.percent;
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').show();
                                    $('#'+id+'-progress').find('.progress-bar').css({"width": percent + "%"});
                                }
                            },
                            FileUploaded: function (up, file, responseObject) {
                                utils.hideloading();
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').hide();
                                }
                                if (responseObject.status === 200) {
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        $('#input-' + id).val(res.url);
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        }
                                    } else {
                                        utils.error(res.error.message);
                                    }
                                } else {
                                    utils.msg('上传服务器无响应！');
                                }
                            },
                            Error: function(up, err) {
                                if(err.code==-200){
                                    utils.msg("文件格式错误，请检查后重新上传!");
                                }
                            }
                        }
                    };
                    var options = $.extend({}, defaultOptions, $option);
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    //上传多媒体
    uploadMedia: function () {
        if ($('.f-uploadmedia').length > 0) {
            In('upload', function () {
                $('.f-uploadmedia').each(function () {
                    var id = $(this).attr('id');
                    /*忽略300毫秒延迟*/
                    $(this).addClass('needsclick');
                    var $option = $(this).data('option'); //maxsize
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '50mb';
                    var ext = $option['ext'] || 'flv,swf,mkv,avi,rm,rmvb,mpeg,mpg,ogg,ogv,mov,wmv,mp4,webm,mp3,wav,mid';
                    var defaultOptions={
                        runtimes: 'html5,flash,html4',
                        multi_selection: false, //不允许多选
                        browse_button: id,
                        url: '/home/upload/file.html?ext_type=vedio',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择文件", extensions: ext}
                            ]
                        },
                        init: {
                            Error:function (uploader,errObject) {
                                utils.error(errObject.message);
                            },
                            FilesAdded: function (up, files) {
                                utils.loading();
                                up.start();
                            },
                            UploadProgress: function(up, file) { //上传中，显示进度条
                                var percent = file.percent;
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').show();
                                    $('#'+id+'-progress').find('.progress-bar').css({"width": percent + "%"});
                                }
                            },
                            FileUploaded: function (up, file, responseObject) {
                                utils.hideloading();
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').hide();
                                }
                                if (responseObject.status === 200) {
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        $('#input-' + id).val(res.url);
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        }
                                    } else {
                                        utils.error(res.error.message);
                                    }
                                } else {
                                    utils.msg('上传服务器无响应！');
                                }
                            },
                            Error: function(up, err) {
                                if(err.code==-200){
                                    utils.msg("文件格式错误，请检查后重新上传!");
                                }
                            }
                        }
                    };
                    var options = $.extend({}, defaultOptions, $option);
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    //多图上传
    uploadMultiImage: function () {
        if ($('.f-upload-images-box').length > 0) {
            In('upload', function () {
                $('.f-upload-images-box').each(function () {
                    var id = $(this).data('upload');
                    /*忽略300毫秒延迟*/
                    $('#'+id).addClass('needsclick');
                    var itemDom=$('#'+id+'-items');
                    var name = $(this).data('name');
                    var $option = $(this).data('option'); //maxsize
                    var datatype = $(this).attr('datatype');
                    if(typeof datatype=='undefined'){
                        datatype='';
                    }else{
                        datatype='datatype="'+datatype+'"';
                    }
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '50mb';
                    var ext = $option['ext'] || 'jpg,gif,png';
                    var defaultOptions={
                        runtimes: 'html5,flash,html4',
                        multi_selection: true, //允许多选
                        browse_button: id,
                        url: '/home/upload/file.html?ext_type=img',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择图片", extensions: ext}
                            ]
                        },
                        resize: {
                            width: 1000,
                            crop: false,
                            quality : 90,
                            preserve_headers: true
                        },
                        init: {
                            Error:function (uploader,errObject) {
                                utils.error(errObject.message);
                            },
                            FilesAdded: function (up, files) {
                                console.log(files);
                                utils.loading();
                                up.start();
                            },
                            UploadProgress: function(up, file) { //上传中，显示进度条
                                var percent = file.percent;
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').show();
                                    $('#'+id+'-progress').find('.progress-bar').css({"width": percent + "%"});
                                }
                            },
                            FileUploaded: function (up, file, responseObject) {
                                utils.hideloading();
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').hide();
                                }
                                if (responseObject.status === 200) {
                                    $('.moxie-shim-html5').hide();
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        } else {
                                            var itemrow = '<div class="item-row">\n' +
                                                '               <input type="hidden" name="' + name + '[]" value="' + res.url + '" '+datatype+'/>\n' +
                                                '               <div class="img-box" style="background-image:url(' + res.url + ')">\n' +
                                                '                    <a class="elem" href="'+res.url+'" style="display:block;width:100%;height:100%;"></a>\n' +
                                                '                    <a href="javascript:;" class="del-icon" onclick="utils.delRow(this);">×</a>\n' +
                                                '               </div>\n' +
                                                '          </div>';
                                            itemDom.append(itemrow);
                                        }
                                    } else {
                                        utils.error(res.error.message);
                                    }
                                } else {
                                    utils.msg('上传服务器无响应！');
                                }
                            }
                        }
                    };
                    var options = $.extend({}, defaultOptions, $option);
                    var uploader = new plupload.Uploader(options);
                    console.log(uploader);
                    uploader.init();
                });
            });
        }
    },
    //多图上传带描述
    uploadMultiImageDesc: function () {
        if ($('.f-upload-images-remark-box').length > 0) {
            In('upload', function () {
                $('.f-upload-images-remark-box').each(function () {
                    var id = $(this).data('upload');
                    /*忽略300毫秒延迟*/
                    $('#'+id).addClass('needsclick');
                    var itemDom=$('#'+id+'-items');
                    var name = $(this).data('name');
                    var dom = $('#' + id);
                    var datatype = $(this).attr('datatype');
                    if(typeof datatype=='undefined'){
                        datatype='';
                    }else{
                        datatype='datatype="'+datatype+'"';
                    }
                    var $option = $(this).data('option'); //maxsize
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '50mb';
                    var ext = $option['ext'] || 'jpg,gif,png';
                    var options={
                        runtimes: 'html5,flash,html4',
                        multi_selection: true, //允许多选
                        browse_button: id,
                        url: '/home/upload/file.html?ext_type=img',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择图片", extensions: ext}
                            ]
                        },
                        resize: {
                            width: 1000,
                            crop: false,
                            quality : 90,
                            preserve_headers: true
                        },
                        init: {
                            Error:function (uploader,errObject) {
                                utils.error(errObject.message);
                            },
                            FilesAdded: function (up, files) {
                                utils.loading();
                                up.start();
                            },
                            UploadProgress: function(up, file) { //上传中，显示进度条
                                var percent = file.percent;
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').show();
                                    $('#'+id+'-progress').find('.progress-bar').css({"width": percent + "%"});
                                }
                            },
                            FileUploaded: function (up, file, responseObject) {
                                utils.hideloading();
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').hide();
                                }
                                if (responseObject.status === 200) {
                                    $('.moxie-shim-html5').hide();
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        } else {
                                            var itemrow = '<div class="col-lg-6 col-md-12 col-sm-12 item-row">\n' +
                                                '               <div class="img-box"  style="background-image:url(' + res.url + ')">\n' +
                                                '                        <a href="javascript:;" onclick="utils.upMove(this);"><i class="fa fa-arrow-left"></i></a>\n' +
                                                '                        <a href="javascript:;" onclick="utils.downMove(this);"><i class="fa fa-arrow-right"></i></a>\n' +
                                                '                        <a href="javascript:;" onclick="utils.delRow(this);"><i class="fa fa-trash-o"></i></a>\n' +
                                                '               </div>\n' +
                                                '               <div class="form">\n' +
                                                '                   <div class="form-group">\n' +
                                                '                        <input type="hidden" class="form-control" name="'+name+'[url][]" value="'+res.url+'" '+datatype+'>\n' +
                                                '                        <input type="text" class="form-control" name="'+name+'[title][]" placeholder="请输入图片标题">\n' +
                                                '                   </div>\n' +
                                                '                   <div class="form-group">\n' +
                                                '                        <textarea class="form-control" rows="2" name="'+name+'[remark][]" placeholder="请输入图片摘要"></textarea>\n' +
                                                '                   </div>\n' +
                                                '                   <div class="input-group link-input">\n' +
                                                '                        <span class="input-group-addon"><i class="fa fa-link"></i></span>\n' +
                                                '                        <input type="text" class="form-control" name="'+name+'[href][]" placeholder="请输入链接地址">\n' +
                                                '                   </div>\n' +
                                                '                </div>\n' +
                                                '          </div>';
                                            itemDom.append(itemrow);
                                        }
                                    } else {
                                        utils.error(res.error.message);
                                    }
                                } else {
                                    utils.msg('上传服务器无响应！');
                                }
                            }
                        }
                    };
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    //多附件上传
    uploadMultiFile: function () {
        if ($('.f-upload-file-box').length > 0) {
            In('upload', function () {
                $('.f-upload-file-box').each(function () {
                    var id = $(this).data('upload');
                    /*忽略300毫秒延迟*/
                    $('#'+id).addClass('needsclick');
                    var itemDom=$('#'+id+'-items');
                    var $option = $(this).data('option'); //maxsize
                    var name = $(this).data('name');
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '50mb';
                    var ext = $option['ext'] || 'rar,zip,tar,gz,7z,bz2,cab,iso,pem,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,md,jpg,jpeg,png,gif';
                    var defaultOptions={
                        runtimes: 'html5,flash,html4',
                        multi_selection: true, //允许多选
                        browse_button: id,
                        url: '/home/upload/file.html?ext_type=file',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择附件", extensions: ext}
                            ]
                        },
                        init: {
                            Error:function (uploader,errObject) {
                                utils.error(errObject.message);
                            },
                            FilesAdded: function (up, files) {
                                utils.loading();
                                up.start();
                            },
                            UploadProgress: function(up, file) { //上传中，显示进度条
                                var percent = file.percent;
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').show();
                                    $('#'+id+'-progress').find('.progress-bar').css({"width": percent + "%"});
                                }
                            },
                            FileUploaded: function (up, file, responseObject) {
                                utils.hideloading();
                                if($('#'+id+'-progress').length>0){
                                    $('#'+id+'-progress').hide();
                                }
                                if (responseObject.status === 200) {
                                    $('.moxie-shim-html5').hide();
                                    var res = JSON.parse(responseObject.response);
                                    console.log(res);
                                    if (res.uploaded == 1) {
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        } else {
                                            var itemrow = '<div class="item-row">\n' +
                                                '<input type="hidden" name="' + name + '[ext][]" value="' + res.ext + '" />\n' +
                                                '<div class="row">\n' +
                                                '<div class="col-sm-4">\n' +
                                                '<div class="input-group pull-left">\n' +
                                                '  <span class="input-group-addon">名称</span>\n' +
                                                '  <input type="text" class="form-control" name="' + name + '[name][]" value="' + res.originalName + '">\n' +
                                                '</div>\n'+
                                                '</div>\n'+
                                                '<div class="col-sm-2">\n' +
                                                '<div class="input-group pull-left">\n' +
                                                '  <input type="text" class="form-control" name="' + name + '[size][]" value="' + res.file_size + '" readonly>\n' +
                                                '  <span class="input-group-addon">Mb</span>\n' +
                                                '</div>\n'+
                                                '</div>\n'+
                                                '<div class="col-sm-6">\n' +
                                                '<div class="input-group pull-left">\n' +
                                                '  <span class="input-group-addon">路径</span>\n' +
                                                '  <input type="text" class="form-control" name="' + name + '[url][]" value="' + res.url + '" readonly>\n' +
                                                '</div>\n'+
                                                '</div>\n'+
                                                '</div>\n'+
                                                '               <div class="action-box">\n' +
                                                '                    <a href="javascript:;" onclick="utils.upMove(this);"><i class="iconfont icon-jiantou-copy1-copy flipy"></i></a>\n' +
                                                '                    <a href="javascript:;" onclick="utils.downMove(this);"><i class="iconfont icon-jiantou-copy1-copy "></i></a>\n' +
                                                '                    <a href="javascript:;" onclick="utils.delRow(this);"><i class="iconfont icon-yduishanchu"></i></a>\n' +
                                                '               </div>\n' +
                                                '          </div>';
                                            itemDom.append(itemrow);
                                        }
                                    } else {
                                        utils.error(res.error.message);
                                    }
                                } else {
                                    utils.msg('上传服务器无响应！');
                                }
                            }
                        }
                    };
                    var options = $.extend({}, defaultOptions, $option);
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    /*tags标签*/
    tags: function () {
        if ($('.f-tags').length > 0) {
            $('.f-tags').each(function () {
                var id = $(this).attr('id');
                var disable = $(this).data('disable');
                var value = $(this).data('value');
                var tag = new Tag(id);
                tag.tagValue  = valid.isEmpty(value)?'':value;
                if(disable){
                    tag.isDisable = true;
                }
                tag.initView();
            });
        }
    },
    inputArray:function(){
        if($('.f-input-array').length >0 ){
            $('.f-input-array').on('click','.btn-del',function () {
                $(this).closest('tr').remove();
                //循环data-row tr重新设置index
                var inputName=$(this).closest('table').data('name');
                $(this).closest('table').find('.data-row tr').each(function (index) {
                    var rowObj=this;
                    $(rowObj).find('.item-input').each(function () {
                        var inputObj = this;
                        var name=$(inputObj).data('name');
                        $(inputObj).attr('name',inputName+'['+index+']'+'['+name+']');
                    });
                });
            });
            $('.f-input-array').on('click','.btn-add',function () {
                var _addObj = this;
                var tdTpl = $(_addObj).closest('.data-row-tpl').find('td');
                var tds=[];
                tdTpl.each(function () {
                    var tdObj = this;
                    if($(tdObj).find('.item-input').length>0){
                        var inputCopy = $(tdObj).find('.item-input').clone(); //查找对应控件
                        inputCopy.attr('value',inputCopy.val());
                        tds.push('<td>'+inputCopy[0].outerHTML+'</td>');
                        $(tdObj).find('.item-input').val(''); //清空控件值
                    }
                });
                tds.push('<td><a href="javascript:;" class="btn btn-danger btn-del"><i class="fa fa-times"></i> </a></td>');
                $(_addObj).closest('table').find('.data-row').append('<tr>'+tds.join('')+'</tr>');
                //循环data-row tr重新设置index
                var inputName=$(this).closest('table').data('name');
                $(this).closest('table').find('.data-row tr').each(function (index) {
                    var rowObj=this;
                    $(rowObj).find('.item-input').each(function () {
                        var inputObj = this;
                        var name=$(inputObj).data('name');
                        $(inputObj).attr('name',inputName+'['+index+']'+'['+name+']');
                    });
                });
            });
        }
    },
    /*单图上传后显示缩略图*/
    showThumb:function (id,data) {
        $('#'+id).addClass('img-upload-over');
        $('#'+id).css('backgroundImage','url('+data.url+')');
    },
    /*单图上传后删除*/
    delimg:function (id) {
        $('#'+id).removeClass('img-upload-over');
        $('#'+id).css('backgroundImage','');
        $('#input-'+id).val('');
    },
    /*音频文件上传*/
    audioUpload:function (id,data) {
        var html='<audio src="'+data.url+'" controls></audio>';
        $('#'+id+'-play').empty().html(html);
    },
    /*视频文件上传*/
    videoUpload:function (id,data) {
        var html='<video src="'+data.url+'" type="video/'+data.ext+'" controls autoplay width="100%"></video>';
        $('#'+id+'-play').empty().html(html);
    }
};
//注册模板使用函数
juicer.register('dateDiff', utils.dateDiff);
juicer.register('dateFormat', utils.dateFormat);
juicer.register('json2string', utils.json2string);
juicer.register('msubstr', utils.msubstr);

function Tag(inputId){
    var obj = new Object();
    if(inputId==null||inputId==""){
        alert("初始化失败，请检查参数！");
        return;
    }
    obj.inputId = inputId;
    //初始化
    obj = (function(obj){
        obj.tagValue="";
        obj.isDisable = false;
        return obj;
    })(obj);

    //初始化界面
    obj.initView=function(){
        var inputObj = $("#"+this.inputId);
        var inputId = this.inputId;
        inputObj.css("display","none");
        var appendStr='';
        appendStr+='<div class="tagsContaine" id="'+inputId+'_tagcontaine">';
        appendStr+='<div class="tagList"></div><div class="edit-box"><input type="text" class="tagInput"/>' +
            '<span class="add-btn"></span></div>';
        appendStr+='</div>';
        inputObj.after(appendStr);
        var tagInput = $("#"+inputId+"_tagcontaine .tagInput");
        if(!this.isDisable){
            $("#"+inputId+"_tagcontaine").attr("ds","1");
            $("#"+inputId+"_tagcontaine").find('.add-btn').click(function () {
                var inputValue = tagInput.val();
                if(inputValue!=''){
                    tagTake.setInputValue(inputId,inputValue);
                    tagInput.val("");
                    tagInput.focus();
                }else{
                    tagInput.focus();
                }
            });
            tagInput.keydown(function(event){
                if(event.keyCode==13){
                    var inputValue = $(this).val();
                    tagTake.setInputValue(inputId,inputValue);
                    $(this).val("");
                }
            });
        }else{
            $("#"+inputId+"_tagcontaine").attr("ds","0");
            $("#"+inputId+"_tagcontaine").find('.edit-box').remove();
        }
        if(this.tagValue!=null&&this.tagValue!=""){
            tagTake.setInputValue(inputId,this.tagValue);
            if(this.isDisable){
                $("#"+inputId+"_tagcontaine .tagList .tagItem .delete").remove();
            }
        }
    }
    obj.disableFun=function(){
        if(this.isDisable){
            return;
        }
        var inputId = this.inputId;
        var tagInput = $("#"+inputId+"_tagcontaine .tagInput");
        tagInput.remove();
        this.isDisable = true;
        $("#"+inputId+"_tagcontaine").attr("ds","0");
        $("#"+inputId+"_tagcontaine .tagList .tagItem .delete").remove();
        tagTake.initTagEvent(inputId);

    }
    obj.unDisableFun = function(){
        if(!this.isDisable){
            return;
        }
        var inputId = this.inputId;
        var tagContaine = $("#"+inputId+"_tagcontaine");
        tagContaine.append('<input type="text" class="tagInput"/>');
        this.isDisable = false;
        $("#"+inputId+"_tagcontaine").attr("ds","1");
        var tagInput = $("#"+inputId+"_tagcontaine .tagInput");
        tagInput.keydown(function(event){
            if(event.keyCode==9){
                var inputValue = $(this).val();
                tagTake.setInputValue(inputId,inputValue);
                $(this).val("");
            }
        });
        $("#"+inputId+"_tagcontaine .tagList .tagItem").append('<div class="delete"></div>');
        tagTake.initTagEvent(inputId);

    }

    return obj;
}
var tagTake ={
    "setInputValue":function(inputId,inputValue){
        if(inputValue==null||inputValue==""){
            return;
        }
        var tagListContaine = $("#"+inputId+"_tagcontaine .tagList");
        inputValue = inputValue.replace(/，/g,",");
        var inputValueArray = inputValue.split(",");
        for(var i=0;i<inputValueArray.length;i++){
            var valueItem = $.trim(inputValueArray[i]);
            if(valueItem!=""){
                var appendListItem = tagTake.getTagItemModel(valueItem);
                tagListContaine.append(appendListItem);
            }
        }
        tagTake.resetTagValue(inputId);
        tagTake.initTagEvent(inputId);
    },
    "initTagEvent":function(inputId){
        $("#"+inputId+"_tagcontaine .tagList .tagItem .delete").off();
        $("#"+inputId+"_tagcontaine .tagList .tagItem").off();
        var ds =  $("#"+inputId+"_tagcontaine").attr("ds");
        if(ds=="0"){
            return;
        }
        $("#"+inputId+"_tagcontaine .tagList .tagItem .delete").mousedown(function(){
            $(this).parent().remove();
            tagTake.resetTagValue(inputId);
        });

        $("#"+inputId+"_tagcontaine .tagList .tagItem").dblclick(function(){
            var tagItemObj = $(this);
            $(this).css("display","none");
            var updateInputObj = $("<input type='text' class='updateInput' value='"+tagItemObj.find("span").html()+"'>");
            updateInputObj.insertAfter(this);
            updateInputObj.focus();
            updateInputObj.blur(function(){
                var inputValue = $(this).val();
                if(inputValue!=null&&inputValue!=""){
                    tagItemObj.find("span").html(inputValue);
                    tagItemObj.css("display","block");
                }else{
                    tagItemObj.remove();
                }
                updateInputObj.remove();
                tagTake.resetTagValue(inputId);
            });
            updateInputObj.keydown(function(event){
                if(event.keyCode==13){
                    var inputValue = $(this).val();
                    if(inputValue!=null&&inputValue!=""){
                        tagItemObj.find("span").html(inputValue);
                        tagItemObj.css("display","block");
                    }else{
                        tagItemObj.remove();
                    }
                    updateInputObj.remove();
                    tagTake.resetTagValue(inputId);
                }
            });
        });
    },
    "resetTagValue":function(inputId){
        var tags = $("#"+inputId+"_tagcontaine .tagList .tagItem");
        var tagsStr="";
        for(var i=0;i<tags.length;i++){
            tagsStr+=tags.eq(i).find("span").html()+",";
        }
        tagsStr = tagsStr.substr(0,tagsStr.length-1);
        $("#"+inputId).val(tagsStr);
    },
    "getTagItemModel":function(valueStr){
        return '<div class="tagItem"><span>'+valueStr+'</span><div class="delete"></div></div>';
    }
}
